(function(){
    var app = angular.module('app', []);


    /*
     *   多选框
     *       callback:   单击触发事件
     *       value:      多选框的值
     *       module:     选中后值由value决定:
     *                       不存在value,module值与多选框选中状态相同,为true或false,
     *                       存在value,module值为数组,value在数组中存在则多选框为选中状态
     * */
    app.directive("check",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与module值相同,为true或false,
            // 存在value,module值为数组,value在数组中存在则check为true反之为false
            template: '<div class="check" ng-class="{disabled:disabled,checked:value === undefined?module:module.indexOf(value) !== -1}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callback : '=',
                module: '=',
                disabled: '=',
                value: '@'
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){
                scope.clickFunc = function() {
                    var check;
                    if(scope.disabled) return;
                    if(scope.value === undefined) {
                        // 不存在value,module值为true或false
                        check = scope.module = !scope.module;
                    } else {
                        // 存在value,module值为数组
                        var index = scope.module.indexOf(scope.value);
                        check = index==-1;
                        if(check) {
                            scope.module.push(scope.value);
                        } else {
                            scope.module.splice(index,1);
                        }
                    }
                    // callback存在则调用callback
                    scope.callback && scope.callback(check, element);
                }
            }
        }
    });
    /*
        checkBox 的选中影响input输入
    */
    app.directive("checkInput",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与module值相同,为true或false,
            // 存在value,module值为数组,value在数组中存在则check为true反之为false
            template: '<div class="checkInput">\
                            <input type="text" class="form-check-input" ng-init="show=true" ng-disabled="module.indexOf(value) != -1" ng-model="moduleInput"/>\
                             <check value="{{value}}" module="module" callback="checkCallback"></check>\
                        </div>',
            scope : {
                callback : '=',
                module: '=',
                value: '@',
                moduleInput:'='
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){

                scope.value = scope.value || undefined;
                scope.checkCallback = function(checked) {
                        scope.callback && scope.callback(checked);
                    //if(!checked) {
                    //    scope.show=false;
                    //} else {
                    //    scope.show=true;
                    //}
                }
            }
        }
    });
    app.directive("dropdownSearch",function(){
        return {
            restrict: 'E',
            template: '<div class="dropdown dropdown-filter" ng-class="{disabled:disabled}">\
                            <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">{{title}}</button>\
                            <span class="caret"></span>\
                            <ul class="dropdown-menu">\
                                <input class="form-control" type="text" ng-model="val"/>\
                                <li onclick="clickFunc({name:all})"><a href="javascript:;">{{all}}</a></il>\
                                <li ng-repeat="item in list | filter: val" onclick="clickFunc(item)"><a title="{{item[nameAttr]}}" href="javascript:;">{{item[nameAttr]}}</a></li>\
                                <li ng-if="list.length == 0"><a style="color: #843534;" href="javascript:;">暂无数据</a></li>\
                            </ul>\
                        </div>',
            replace: true,
            scope:{
                title:"@",
                list:"=",
                nameAttr:"@",
                callback:"=",
                placeholder: "@",
                disabled: "=",
                idAttr: "@",
                all: "@"
            },
            link: function(scope,element,attrs){
                scope.nameAttr = scope.nameAttr || "name";
                scope.idAttr = scope.idAttr || "id";
                scope.all = scope.all || scope.title;
                scope.clickFunc = function (item) {
                    scope.title = item[scope.nameAttr];
                    scope.val = "";
                    scope.callback && scope.callback(item);
                }
            }
        };
    })
    /*
     *   单选框
     *       callback:   单击触发事件
     *       value:      单选框的值
     *       module:     选中后值由value决定
     * */
    app.directive("radio",function(){
        return {
            restrict: 'E',
            template: '<div class="radio" ng-class="{disabled:disabled,checked:module==value}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callback : '=',
                module: '=',
                disabled: '=',
                value: '@'
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){
                scope.clickFunc = function(){
                    if(scope.disabled) return;
                    if(scope.module == scope.value) return;
                    scope.module = scope.value;
                    scope.callback && scope.callback(scope.module);
                }
            }
        }
    });


    /**
     *  切换按钮
     *      callback    回调函数,单击触发
     *      module      按钮的状态,true或者false
     */
    app.directive("switch",function(){
        return {
            restrict: 'E',
            template: '<div class="switch" ng-class="{open:value.open}" onclick="clickFunc()"></div>',
            scope : {
                callback : '=',
                value: "=",
                index:'@',
                swDisabled:'=',
            },
            replace: true,
            link:function(scope, element, attrs){
                // 设置默认值
                scope.value = scope.value || {open:true};
                scope.index = scope.index || 0;
                scope.clickFunc = function(){
                    if(scope.swDisabled) return layer.msg("您没有编辑权限！");
                    scope.value.open = !scope.value.open;
                    scope.callback && scope.callback(scope.value,scope.index);
                }
            }
        }
    });


    /**
     *  下拉框
     *      title       下拉框标题
     *      nameAttr    字符串,list显示文字的属性,默认为name
     *      list        对象数组.下拉框内容
     *          list[i][nameAttr]    下拉框显示的文字,nameAttr默认为name
     *      callback(item)    回调函数.单击下拉框后触发
     *          item    被点击的list[i]对象
     */
    app.directive("dropdownFilter",function(){
        return {
            restrict: 'E',
            template: '<div class="dropdown dropdown-filter" ng-class="{disabled:disabled}">\
                            <button class="btn btn-default dropdown-toggle cl" data-toggle="dropdown">\
                                <span style="width: 55%; display: inline-block;">{{title}}</span>\
                                <span ng-show="publish" class="estimate">\
                                    <span>流量占比：{{currEstimate * 100 | number:2}}%</span>\
                                    <span style="width: {{currEstimate * 100 | number:2}}%"></span>\
                                </span>\
                            </button>\
                            <span class="caret"></span>\
                            <ul class="dropdown-menu">\
                                <li class="cl" ng-repeat="item in list" onclick="clickFunc(item)">\
                                    <a title="{{item[nameAttr]}}" href="javascript:;">{{item[nameAttr]}}</a>\
                                    <span ng-show="publish" class="estimate fl">\
                                        <span>流量占比：{{estimate[item.templateId] * 100 | number:2}}%</span>\
                                        <span style="width: {{estimate[item.templateId] * 100 | number:2}}%"></span>\
                                    </span>\
                                </li>\
                            </ul>\
                        </div>',
            replace: true,
            scope:{
                title:"=",
                list:"=",
                nameAttr:"@",
                callback:"=",
                disabled:"=",
                publish: "=",
                estimate: "=",
                currEstimate: "="
            },
            link: function(scope,element,attrs){
                // 删除title  防止显示angular指令
                element.removeAttr("title");
                scope.nameAttr = scope.nameAttr || "name";

                scope.clickFunc = function (item) {
                    scope.title = item[scope.nameAttr];
                    if (scope.publish) {
                        scope.currEstimate = scope.estimate[item.templateId];
                    }
                    scope.callback && scope.callback(item);
                }
            }
        };
    });


    /**
     *  输入下拉框
     *      value       输入框的值
     *      nameAttr    字符串,list显示文字的属性,默认为name
     *      list        对象数组.下拉框内容
     *          list[i][nameAttr]    下拉框显示的文字,nameAttr默认为name
     *      clickCallback(item)    回调函数,点击下拉框触发
     *          item    被点击的list[i]对象
     *      blurCallback(value)    回调函数,输入框失去焦点触发
     *          value   输入框的值
     */
    app.directive("dropdownFilterInput",function(){
        return {
            restrict: 'E',
            template: '<div class="dropdown dropdown-input">\
                            <input class="form-control dropdown-toggle" data-toggle="dropdown" ng-blur="blurFunc(value)" ng-model="value" ng-keyup="keyUp($event,value)" placeholder="{{placeholder}}"/>\
                            <span class="caret"></span>\
                            <ul class="dropdown-menu">\
                                <li ng-show="list.length == 0">内容为空</li>\
                                <li ng-repeat="item in list | filter:hasName" onclick="clickFunc(item)"><a href="javascript:;">{{item[nameAttr]}}</a></li>\
                            </ul>\
                        </div>',
            replace: true,
            scope:{
                value:"=",
                list:"=",
                clickCallback:"=",
                blurCallback:"=",
                placeholder: '@',
                keyUpCallback:'=',
            },
            link: function(scope,element,attrs){
                scope.nameAttr = scope.nameAttr || "name";
                scope.hasName = function(item){
                    return item[scope.nameAttr].indexOf(scope.value) != -1
                }
                scope.clickFunc = function (item) {
                    scope.value = item[scope.nameAttr];
                    scope.clickCallback && scope.clickCallback(item);
                }
                scope.blurFunc = function (item) {
                    scope.blurCallback && scope.blurCallback(item);
                }
                scope.keyUp = function ($event,item) {
                    scope.keyUpCallback && scope.keyUpCallback($event,item);
                }
            }
        };

    });
    /**
     *  多选搜索下拉框
     *      title       下拉框标题
     *      nameAttr    字符串,list显示文字的属性,默认为name
     *      list        对象数组.下拉框内容
     *          list[i][nameAttr]    下拉框显示的文字,nameAttr默认为name
     *      module  多选框对象,等同于checkmodule
     *      clickCallback(item)    回调函数,点击下拉框触发
     *          item    被点击的list[i]对象
     */
    app.directive("dropdownCheckSearchFilter",function(){
        return {
            restrict: 'E',
            template: '<div class="dropdown dropdown-check-filter">\
                            <button class="btn btn-default dropdown-toggle bs" type="button" data-toggle="dropdown">\
                                <span class="dropdown-value">{{title}}</span><span class="caret"></span>\
                            </button>\
                            <div class="dropdown-menu" role="menu">\
                                <ul onclick="stop($event)">\
                                    <li><input class="form-control search" ng-model="value"></li>\
                                    <li ng-repeat="item in list| filter: hasName" ><check module="module" callback="checkFunc" value="{{item}}">{{item[nameAttr]}}</check></li>\
                                </ul>\
                                <div class="dropdown-btn" onclick="clickFunc()">确认</div>\
                            </div>\
                        </div>',
            replace: true,
            scope:{
                title:"@",
                list:"=",
                module:"=",
                nameAttr:"@",
                callback:"=",
                checkCallback:"="
            },
            link: function(scope,element,attrs){
                // 删除title  防止显示angular指令
                element.removeAttr("title");
                scope.nameAttr = scope.nameAttr || "name";
                scope.value = "";
                scope.hasName = function(item){
                    return item[scope.nameAttr].indexOf(scope.value) != -1
                }
                scope.clickFunc = function () {
                    $(".dropdown-check-filter").removeClass("open")
                    scope.value = "";
                    scope.callback && scope.callback(scope.module);
                }
                scope.checkFunc = function(){
                    scope.checkCallback && scope.checkCallback(scope.module);
                }
                scope.stop = function(e) {
                    e.stopPropagation();
                }
            }
        };
    });
/*-----------------------------------------------------------------*/
    app.directive("checkone",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与onemodule值相同,为true或false,
            // 存在value,onemodule值为数组,value在数组中存在则check为true反之为false
            template: '<div class="check" ng-class="{checked:onemodule.indexOf(value)>-1?true:false}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callbackAll : '=',
                // allmodule:"=",
                onemodule: '=',
                disabled: '=',
                value: '@'
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){
                scope.clickFunc = function() {
                    var check;
                    // console.log(scope,element, attrs)
                    if(scope.disabled) return;
                    var index = scope.onemodule.indexOf(scope.value);
                    check = index==-1;
                    if(check) {
                        scope.onemodule.push(scope.value);    
                        if(scope.$parent.$parent.allactivitymodule){
                            scope.$parent.$parent.allactivitymodule = [];
                        }                                           
                    } else {
                        scope.onemodule.splice(index,1);                        
                        if(scope.onemodule.length != 0){
                            scope.onemodule[scope.onemodule.length-1].isAll = false;
                        }
                    }
                    scope.nList = [];
                    scope.$parent.list.forEach(function(v,k){
                        scope.nList[k] = {};
                        scope.nList[k].id = v.id;
                        scope.nList[k].name = v.name;
                        scope.nList[k] = JSON.stringify(scope.nList[k])
                    })
                    // console.log(scope.onemodule.length,scope.nList.length)
                    if(scope.onemodule.length-1 == scope.nList.length) {
                        scope.$parent.$parent.allmodule = ['all']
                    }else{
                        scope.$parent.$parent.allmodule = [];
                    }
                    // callback存在则调用callback
                    scope.callback && scope.callback(check, element);
                }
            }
        }
    });
    app.directive("checkall",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与allmodule值相同,为true或false,
            // 存在value,allmodule值为数组,value在数组中存在则check为true反之为false
            template: '<div class="check" ng-class="{checked:allmodule.indexOf(value)>-1?true:false}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callbackAll : '=',
                allmodule:"=",
                // module: '=',
                disabled: '=',
                value: '@'
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){
                scope.clickFunc = function() {
                    var check;
                    // console.log(scope,element, attrs)
                    if(scope.disabled) return;
                    var index = scope.allmodule.indexOf(scope.value);
                    check = index==-1;
                    if(check) {
                        scope.allmodule.push(scope.value);
                        if(scope.$parent.list) {
                            scope.nList = [];
                            scope.$parent.list.forEach(function(v,k){
                                scope.nList[k] = {};
                                scope.nList[k].id = v.id;
                                scope.nList[k].name = v.name;
                                scope.nList[k] = JSON.stringify(scope.nList[k])
                            })
                            scope.$parent.onemodule = scope.nList;
                            scope.$parent.onemodule.push({isAll: true});
                            // scope.$parent.allactivitymodule = [];
                        }
                        if(scope.$parent.allactivitymodule){
                            scope.$parent.allactivitymodule = [];
                        }
                    } else {
                        scope.allmodule.splice(index,1);
                        scope.$parent.onemodule = [];
                    }
                    // callback存在则调用callback
                    scope.callback && scope.callback(check, element);
                }
            }
        }
    });
    app.directive("checkedone",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与allactivitymodule值相同,为true或false,
            // 存在value,allactivitymodule值为数组,value在数组中存在则check为true反之为false
            template: '<div class="check" ng-class="{checked:allactivitymodule.indexOf(value)>-1?true:false}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callbackAll : '=',
                // allmodule:"=",
                allactivitymodule: '=',
                disabled: '=',
                value: '@'
            },
            replace: true,
            transclude: true,
            link:function(scope, element, attrs){
                scope.clickFunc = function() {
                    var check;
                    // console.log(scope,element, attrs)
                    if(scope.disabled) return;
                    var index = scope.allactivitymodule.indexOf(scope.value);
                    check = index==-1;
                    if(check) {
                        scope.allactivitymodule.push(scope.value); 
                        scope.$parent.$parent.onemodule = []; 
                        scope.$parent.$parent.allmodule = [];                      
                    } else {
                        scope.allactivitymodule.splice(index,1);
                    }
                    // callback存在则调用callback
                    scope.callback && scope.callback(check, element);
                }
            }
        }
    });
    /**--------------------------------------------------
     *  多选全选搜索下拉框
     *      placeholder      
     *      id          为1时显示checkedone 
     *      type        下拉款类型
     *      onemodule   多选数组 
     *      title       下拉框标题
     *      allmodule   全选数组（所有）
     *      allactivitymodule  全选数组（活跃）
     *      all         （全选）名称
     *      activity    （活跃）名称
     *      nameAttr    字符串,list显示文字的属性,默认为name
     *      list        对象数组.下拉框内容
     *          list[i][nameAttr]    下拉框显示的文字,nameAttr默认为name
     *      module  多选框对象,等同于checkmodule
     *      clickCallback(item)    回调函数,点击下拉框触发
     *          item    被点击的list[i]对象
     */
    app.directive("dropdownCheckAllSearchFilter",function(){
        return {
            restrict: 'E',
            template: '<div class="dropdown dropdown-check-filter">\
                            <button class="btn btn-default dropdown-toggle bs" type="button" data-toggle="dropdown">\
                                <span class="dropdown-value">{{title}}</span><span class="caret"></span>\
                            </button>\
                            <div class="dropdown-menu" role="menu">\
                                <ul onclick="stop($event)">\
                                    <li><checkall allmodule="allmodule" value="all">{{all[0].name}}</checkall></li>\
                                </ul>\
                                <ul onclick="stop($event)">\
                                    <li ng-if="id !=1"><checkedone allactivitymodule="allactivitymodule" value="{{type}}">{{activity[0].name}}</checkedone></li>\
                                </ul>\
                                <ul onclick="stop($event)">\
                                    <li><input class="form-control search" ng-model="value" placeholder="{{placeholder}}"></li>\
                                    <li ng-repeat="item in list| filter: hasName" title="{{item[nameAttr]}}"><checkone onemodule="onemodule" callback="checkFunc" value="{{item}}">{{item[nameAttr]}}</checkone></li>\
                                </ul>\
                                <div class="dropdown-btn" onclick="clickFunc()">确认</div>\
                            </div>\
                        </div>',
            replace: true,
            scope:{
                placeholder:"@",
                title:"@",
                id:"@",
                type:"@",
                list:"=",
                module:"=",
                onemodule:"=",
                allmodule:"=",
                allactivitymodule:"=",
                all:"=",
                activity:"=",
                nameAttr:"@",
                callback:"=",
                checkCallback:"="
            },
            link: function(scope,element,attrs){
                // 删除title  防止显示angular指令
                element.removeAttr("title");
                scope.nameAttr = scope.nameAttr || "name";
                scope.value = "";
                scope.hasName = function(item){
                    return item[scope.nameAttr].indexOf(scope.value) != -1
                }
                scope.clickFunc = function () {
                    $(".dropdown-check-filter").removeClass("open")
                    scope.value = "";
                    scope.callback && scope.callback(scope.module);
                }
                scope.checkFunc = function(){
                    scope.checkCallback && scope.checkCallback(scope.module);
                }
                scope.stop = function(e) {
                    e.stopPropagation();
                }              
            }
        };
    });

    app.directive('ngCopyable', function($document) {
        return {
            restrict: 'A',
            scope: {
                copyText: '='
            },
            link: function(scope, element, attrs){
                //点击事件
                element.bind('click', function(){
                    //创建将被复制的内容
                    $document.find('body').eq(0).append('<div id="ngCopyableId">' + scope.copyText + '</div>');
                    var newElem = angular.element(document.getElementById('ngCopyableId'))[0];

                    var range = document.createRange();
                    range.selectNode(newElem);
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(range);
                    var successful = document.execCommand('copy');

                    //执行完毕删除
                    var oldElem = document.getElementById('ngCopyableId');
                    oldElem.parentNode.removeChild(oldElem);
                    window.getSelection().removeAllRanges();

                    //提示
                    if (successful) {
                        layer.msg('已成功复制');
                    } else {
                        layer.msg('浏览器不支持复制');

                    }

                });
            }

        };
    });
    /**
     *  搜索框
     *      value               输入框的值
     *      placeholder         输入框的placeholder
     *      clickCallback(item) 回调函数,点击搜索按钮时触发
     *      blurCallback(item)  回调函数,输入框失去焦点时触发
     *      keyupCallback(item) 回调函数,输入框按钮up时触发
     */
    app.directive("search",function(){
        return {
            restrict: 'E',
            template: '<div class="search">\
                            <input class="form-control search-input" type="text" ng-model="value" placeholder="{{placeholder}}" ng-keyup="keyupFunc($event)"/>\
                            <i class="search-icon" onclick="clickFunc()"></i>\
                        </div>',
            replace: true,
            scope:{
                value:"=",
                callback:"=",
                placeholder: '@'
            },
            link: function(scope,element,attrs){
                scope.clickFunc = function (item) {
                    scope.callback && scope.callback(scope.value);
                }
                scope.keyupFunc = function (e) {
                    if(e.keyCode == 13) {
                        scope.callback && scope.callback(scope.value);
                    }
                }
            }
        };

    });
    /**
     *  时间下拉框
     *      callback(sTime,eTime)    回调函数,选择时间时触发
     *              sTime   选择的开始时间,格式为YYYY-MM-DD
     *              eTime   选择的结束时间,格式为YYYY-MM-DD
     */
    app.directive("dropdownDate",function(){
        return {
            restrice: 'E',
            template:'<div class="dropdown dropdown-date">\
                        <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">{{now}}</button>\
                        <span class="caret"></span>\
                        <ul class="dropdown-menu wr">\
                            <li ng-if="hasAll" onclick="selectDate(0)"><a href="javascript:;">全部时间段</a></li>\
                            <li onclick="selectDate(1)"><a href="javascript:;">{{tody}}</a></li>\
                            <li onclick="selectDate(2)"><a href="javascript:;">{{yesterday}}</a></li>\
                            <li onclick="selectDate(3)"><a href="javascript:;">{{lastWeek}}</a></li>\
                            <li onclick="selectDate(4)"><a href="javascript:;">{{lastTwo}}</a></li>\
                            <li class="li_time">\
                                <a href="javascript:;" class="cl">\
                                    <span class="fl"><input onclick="calendar($event)" type="text" readonly="readonly" class="startTime" placeholder="选择开始时间..." /><i class="icon_time"></i></span>\
                                    <em class="fl">-</em>\
                                    <span class="fl"><input onclick="calendar($event)" type="text" readonly="readonly" class="endTime" placeholder="选择结束时间..." /><i class="icon_time"></i></span>\
                                    <span class="fl"><input  onclick="selectDate(5)" type="button" value="确认选择" class="affirm"/></span>\
                                </a>\
                            </li>\
                        </ul>\
                    </div>',
            replace: true,
            scope : {
                callback : '=',
                hasAll:'@'
            },
            link: function(scope, element, attrs) {
                scope.hasAll = scope.hasAll || false;
                //scope.eTime = scope.sTime = getNowFormatDate();
                var date = new Date();
                var lastWeek = new Date(date.getTime() - 6 * 24 * 3600 * 1000);
                var lastTwo = new Date(date.getTime() - 13 * 24 * 3600 * 1000);
                var tody = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                lastWeek = lastWeek.getFullYear() + "-" + (lastWeek.getMonth() + 1) + "-" + lastWeek.getDate();
                lastTwo = lastTwo.getFullYear() + "-" + (lastTwo.getMonth() + 1) + "-" + lastTwo.getDate();
                var yesterday = nextDayFnc(getNowFormatDate(), 1, 1);
                // 借用nextDayFnc方法将XXXX-X-X转化成XXXX-0X-0X格式
                tody = nextDayFnc(tody,0,1);
                lastWeek = nextDayFnc(lastWeek,0,1);
                lastTwo = nextDayFnc(lastTwo,0,1);
                scope.tody = "今日："+parseDate(tody);
                scope.now = scope.hasAll?"全部时间段":scope.tody;
                scope.yesterday = "昨日：" + parseDate(yesterday);
                scope.lastWeek = "最近7日：" + parseDate(lastWeek) + " — " + parseDate(tody);
                scope.lastTwo = "最近14日：" + parseDate(lastTwo) + " — " + parseDate(tody);

                //隐藏时间控件
                $(document).click(function (event) {
                    $("#__calendarPanel").css("visibility","hidden");
                    $(".entrance").find("ul").hide();
                    $(".scrollBar").hide();
                    $(".entrance").removeClass("quick_active");
                    $(".entrance").css({
                        "background": "url('images/index_btn_bg2.png') no-repeat",
                        "border-radius": "0px 0px 5px 5px"
                    });
                    $(".apps_logo").css("background", "url('images/index_app_icon.png') no-repeat");
                    $(".small_font").parent().css("border-color", "#fff");
                });
                //时间控件
                var calendar = new Calendar();
                $(".startTime, .endTime").click(function (event) {
                    event.stopPropagation();
                });

                // 根据type判断选择的日期
                scope.selectDate = function(type){
                    var start,end = tody;
                    switch (type) {
                        case 0:
                            scope.now = "全部时间段";
                            start = end = "";
                            break;
                        case 1:
                            // 今日
                            scope.now = scope.tody;
                            start = tody;
                            break;
                        case 2:
                            // 昨日
                            scope.now = scope.yesterday;
                            start = end = yesterday;
                            break;
                        case 3:
                            // 上周
                            scope.now = scope.lastWeek;
                            start = lastWeek;
                            break;
                        case 4:
                            // 上两周
                            scope.now = scope.lastTwo;
                            start = lastTwo;
                            break;
                        case 5:
                            // 自定义日期
                            // jQlite的find方法根据类名查找有bug,改用jquery
                            var $this = $(element[0]);
                            start = $this.find(".startTime").val(),
                                end = $this.find(".endTime").val();
                            if(!start || !end) {
                                return layer.msg("请先选择时间");
                            }
                            scope.now = "时间为："+parseDate(start)+" — "+parseDate(end);
                            $this.removeClass("open");
                            break;
                    }
                    scope.callback && scope.callback(start,end,type)
                }
                scope.calendar = function(e){
                    new Calendar().show(e.target);
                }
            }
        }
        //获取当前时间戳 reutrn YYYY-MM-DD
        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            //var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();

            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }


            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;

            return currentdate;

        };
        //传入一个  YYYYY-MM-DD  前推和后退数以天数
        function nextDayFnc(startTime,y,z){
            var startTime = startTime;
            var startTime2 = startTime.split("-");
            var year = parseInt(startTime2[0]);
            var month = parseInt(startTime2[1]);
            var day = parseInt(startTime2[2]);
            var myDate=new Date();
            var setYesDay =  parseInt(myDate.setFullYear(year,month-1,day));
            if(z==1){
                var yesterday = parseInt(setYesDay-86400000*y);     //加减天数改变这个毫秒数
            }else if(z==2){
                var yesterday = parseInt(setYesDay+86400000*y);      //z==1时为-  z==2时为+
            }
            var ds = new Date(yesterday);
            var oldYear=ds.getYear()+1900;
            var oldMonth = ds.getMonth()+1;
            if (oldMonth<10){
                oldMonth = "0"+oldMonth;
            }else{
                oldMonth = oldMonth;
            }
            var oldDay = ds.getDate();
            if(oldDay<10){
                oldDay = "0"+oldDay;
            }else{
                oldDay = oldDay;
            }
            var yesDay = oldYear+"-"+oldMonth+"-"+oldDay;
            return yesDay;
        };
        //传入 YYYYY-MM-DD 转成 yyyy年mm月dd日
        function parseDate(date){
            var newDate = date.split("-");
            return newDate[0]+"年"+newDate[1]+"月"+newDate[2]+"日";
        }
    });

    /**
     *  时间下拉框
     *      callback(sTime,eTime)    回调函数,选择时间时触发
     *              sTime   选择的开始时间,格式为YYYY-MM-DD
     *              eTime   选择的结束时间,格式为YYYY-MM-DD
     */
    app.directive("dropdownDateo",function(){
        return {
            restrice: 'E',
            template:'<div class="dropdown dropdown-date">\
                        <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">{{now}}</button>\
                        <span class="caret"></span>\
                        <ul class="dropdown-menu wr">\
                            <li onclick="selectDate(0)"><a href="javascript:;">{{yesterday}}</a></li>\
                            <li onclick="selectDate(1)"><a href="javascript:;">{{tody}}</a></li>\
                            <li onclick="selectDate(2)"><a href="javascript:;">{{thisWeek}}</a></li>\
                        </ul>\
                    </div>',
            replace: true,
            scope : {
                callback : '=',
                hasAll:'@'
            },
            link: function(scope, element, attrs) {
                scope.hasAll = scope.hasAll || false;
                //scope.eTime = scope.sTime = getNowFormatDate();
                var date = new Date();
                var thisWeek = {};            
                var tody = getNowFormatDate();
                var yesterday = date.setDate(date.getDate() - 1);
                yesterday = date.format("yyyy-MM-dd")
                tody = nextDayFnc(tody,0,1);
                thisWeek.start = getTime(0,1);
                thisWeek.end = getTime(-6,1);                
                scope.tody = "今日："+ parseDate(tody);
                scope.yesterday = "昨日：" + parseDate(yesterday);
                scope.thisWeek = "本周：" + parseDate(thisWeek.start) + " — " + parseDate(thisWeek.end);
                scope.now = scope.hasAll?scope.yesterday:scope.yesterday;
                // 根据type判断选择的日期
                scope.selectDate = function(type){
                    var start,end = tody;
                    switch (type) {
                        case 0:
                            // 昨日
                            scope.now = scope.yesterday;
                            start = end = yesterday;
                            break;
                        case 1:
                            // 今日
                            scope.now = scope.tody;
                            start = end = tody;
                            break;
                        case 2:
                            // 本周
                            scope.now = scope.thisWeek;
                            start = thisWeek.start;
                            end =  thisWeek.end;
                            break;
                    }
                    scope.callback && scope.callback(start,end,type)
                }
                scope.calendar = function(e){
                    new Calendar().show(e.target);
                }
            }
        }
        //获取当前时间戳 reutrn YYYY-MM-DD
        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            //var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();

            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }


            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;

            return currentdate;

        };
        //传入一个  YYYYY-MM-DD  前推和后退数以天数
        function nextDayFnc(startTime,y,z){
            var startTime = startTime;
            var startTime2 = startTime.split("-");
            var year = parseInt(startTime2[0]);
            var month = parseInt(startTime2[1]);
            var day = parseInt(startTime2[2]);
            var myDate=new Date();
            var setYesDay =  parseInt(myDate.setFullYear(year,month-1,day));
            if(z==1){
                var yesterday = parseInt(setYesDay-86400000*y);     //加减天数改变这个毫秒数
            }else if(z==2){
                var yesterday = parseInt(setYesDay+86400000*y);      //z==1时为-  z==2时为+
            }
            var ds = new Date(yesterday);
            var oldYear=ds.getYear()+1900;
            var oldMonth = ds.getMonth()+1;
            if (oldMonth<10){
                oldMonth = "0"+oldMonth;
            }else{
                oldMonth = oldMonth;
            }
            var oldDay = ds.getDate();
            if(oldDay<10){
                oldDay = "0"+oldDay;
            }else{
                oldDay = oldDay;
            }
            var yesDay = oldYear+"-"+oldMonth+"-"+oldDay;
            return yesDay;
        };
        //传入 YYYYY-MM-DD 转成 yyyy年mm月dd日
        function parseDate(date){
            var newDate = date.split("-");
            return newDate[0]+"年"+newDate[1]+"月"+newDate[2]+"日";
        }
        /***参数都是以周一为基准的 上周的开始时间 getTime(7,1) 上周的结束时间 getTime(1,1) 本周的开始时间 getTime(0,1) 本周的结束时间 getTime(-6,1)***/
        function getTime(n,m) {
            var now = new Date();
            var year = now.getFullYear();
            //因为月份是从0开始的,所以获取这个月的月份数要加1才行
            var month = now.getMonth() + 1;
            var date = now.getDate();
            var day = now.getDay();
            // console.log(date);
            //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
            if (day !== 0) {
                n = n + (day - 1);
            } else {
                n = n + day;
            }
            if (day) {
                //这个判断是为了解决跨年的问题
                if (month > 1) {
                    month = month;
                }
                //这个判断是为了解决跨年的问题,月份是从0开始的
                else {
                    year = year - 1;
                    month = 12;
                }
            }
            now.setDate(now.getDate() - n);
            year = now.getFullYear();
            month = now.getMonth() + 1;
            date = now.getDate();
            // console.log(n);
            if(m == 1) {
                s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date); //m=1,2018-01-01
            } else if(m == 2){
                s = year + "年" + (month < 10 ? ('0' + month) : month) + "月" + (date < 10 ? ('0' + date) : date) + '日'; //m=2,2018年01月01日
            }     
            return s;
        };
    });
    
    /**
     *  地域控件中复选框联动
     *
     */
    app.directive("areaCheck",function(){
        return {
            restrict: 'E',
            // 不存在value,check值与module值相同,为true或false,
            // 存在value,module值为数组,value在数组中存在则check为true反之为false
            template: '<div class="check araeCheck" ng-class="{checked:value === undefined?module:module.indexOf(value) !== -1}" onclick="clickFunc()"><b></b><span ng-transclude></span></div>',
            scope : {
                callback : '=',
                module: '=',
                value: '@',
                pid: "@",
                grandpid: "@",
                item: "@",
                areaName: "=",
                areaId: "=",
            },
            replace: true,
            transclude: true,
            link:function(scope, e, attrs){
                scope.clickFunc = function() {
                    var check;
                    if(scope.value === undefined) {
                        // 不存在value,module值为true或false
                        check = scope.module = !scope.module;
                    } else {
                        // 存在value,module值为数组
                        var index = scope.module.indexOf(scope.value);
                        check = index==-1;
                        if(check) {
                            scope.module.push(scope.value);
                        } else {
                            scope.module.splice(index,1);
                        }
                    }
                    var c = check;
                    var item = JSON.parse(scope.item);
                    var _this = $(e[0]);
                    var id = _this.attr("value");
                    var pid = _this.attr("pid");
                    var grandpid = _this.attr("grandpid");
                    var flag;
                    if (!pid && !grandpid) {//点一级
                        var checks = $(".check[pid='"+ id +"'], .check[grandpid='"+ id +"']");
                        if (c) {
                            scope.areaName.push(item.name);
                            scope.areaId.push(item.id);
                            for (var i = 0; i < checks.length; i++) {
                                var index = scope.module.indexOf(checks.eq(i).attr("value"));
                                if (index == -1)
                                    scope.module.push(checks.eq(i).attr("value"));
                                index = scope.areaId.indexOf(checks.eq(i).attr("value") * 1);
                                if (index != -1) {
                                    scope.areaName.splice(index, 1);
                                    scope.areaId.splice(index, 1);
                                }
                            }
                        } else {
                            var index = scope.module.indexOf(id);
                            if (index != -1) scope.module.splice(index, 1);
                            for (var i = 0; i < checks.length; i++) {
                                index = scope.module.indexOf(checks.eq(i).attr("value"));
                                if (index != -1) scope.module.splice(index, 1);
                                index = scope.areaId.indexOf(checks.eq(i).attr("value") * 1);
                                if (index != -1) {
                                    scope.areaName.splice(index, 1);
                                    scope.areaId.splice(index, 1);
                                }
                            }
                            index = scope.areaName.indexOf(item.name);
                            if (index != -1) {
                                scope.areaName.splice(index, 1);
                                scope.areaId.splice(index, 1);
                            }
                        }
                    } else if (pid != undefined && !grandpid) {//点二级
                        var checks = $(".check[pid='"+ id +"']");
                        var parent = JSON.parse($(".araeCheck[value='"+ pid +"']").attr("item"));
                        if (c) {
                            scope.areaName.push(item.name);
                            scope.areaId.push(item.id);
                            for (var i = 0; i < checks.length; i++) {
                                var index = scope.module.indexOf(checks.eq(i).attr("value"));
                                if (index == -1)
                                    scope.module.push(checks.eq(i).attr("value"));
                            }
                            var subs = $(".check[pid='"+ pid +"']");
                            var checkeds = $(".checked[pid='"+ pid +"']");
                            if (subs.length == (checkeds.length + 1) && scope.module.indexOf(pid) == -1) {
                                index = scope.module.indexOf(pid);
                                if (index == -1)
                                    scope.module.push(pid);
                                subs = $(".check[pid='"+ pid +"'], .check[grandpid='"+ pid +"']");
                                for (var i = 0; i < subs.length; i++) {
                                    var index = scope.areaId.indexOf(subs.eq(i).attr("value") * 1);
                                    if (index != -1) {
                                        scope.areaName.splice(index, 1);
                                        scope.areaId.splice(index, 1);
                                    }
                                }
                                scope.areaName.push(parent.name);
                                scope.areaId.push(parent.id);
                            }
                        } else {
                            for (var i = 0; i < checks.length; i++) {
                                index = scope.module.indexOf(checks.eq(i).attr("value"));
                                if (index != -1) scope.module.splice(index, 1);
                                index = scope.areaId.indexOf(checks.eq(i).attr("value") * 1);
                                if (index != -1) {
                                    scope.areaName.splice(index, 1);
                                    scope.areaId.splice(index, 1);
                                }
                            }
                            index = scope.module.indexOf(pid);
                            if (index != -1) scope.module.splice(index, 1);

                            index = scope.areaName.indexOf(item.name);
                            if (index != -1) {
                                scope.areaName.splice(index, 1);
                                scope.areaId.splice(index, 1);
                            }

                            index = scope.areaName.indexOf(parent.name);
                            if (index != -1) {
                                scope.areaName.splice(index, 1);
                                scope.areaId.splice(index, 1);
                            }
                            var subChecks = $(".checked[pid='"+ parent.id +"']");
                            for (var i = 0; i < subChecks.length; i++) {
                                var val = JSON.parse(subChecks.eq(i).attr("item"));
                                index = scope.areaName.indexOf(val.name);
                                flag = index == -1 && subChecks.eq(i).attr("pid") != item.id && subChecks.eq(i).attr("value") != id;
                                if (flag) {
                                    scope.areaName.push(val.name);
                                    scope.areaId.push(val.id);
                                }
                            }
                        }
                    } else if (pid != undefined && grandpid != undefined) { //点三级
                        if (c) {
                            scope.areaName.push(item.name);
                            scope.areaId.push(item.id);
                            var subs = $(".check[pid='"+ pid +"']");
                            var checkeds = $(".checked[pid='"+ pid +"']");
                            if (subs.length == (checkeds.length + 1)) {
                                var index = scope.module.indexOf(pid);
                                if (index == -1)
                                    scope.module.push(pid);
                            }
                            var subLen1 = $(".check[pid='"+ grandpid +"']").length;
                            var checkLen1 = $(".checked[pid='"+ grandpid +"']").length;
                            if (subLen1 == (checkLen1 + 1) && scope.module.indexOf(grandpid) == -1) {
                                scope.module.push(grandpid);
                            }
                        } else {
                            index = scope.module.indexOf(pid);
                            if (index != -1) scope.module.splice(index, 1);
                            index = scope.module.indexOf(grandpid);
                            if (index != -1) scope.module.splice(index, 1);
                            index = scope.areaName.indexOf(item.name);
                            if (index != -1) {
                                scope.areaName.splice(index, 1);
                                scope.areaId.splice(index, 1);
                            }
                        }
                    }
                    // callback存在则调用callback
                    scope.callback && scope.callback(e);
                }
            }
        }
    });
    //省市定向
    app.directive('positionCustom', function () {
        return {
            restrict: "E",
            template: '<div class="custom-box cl">\
                           <div class="left fl">\
                             <div class="cus-title">\
                                可选项目\
                                <i class="icon-search" ng-if="config.searchIcon" onclick="config.search()"></i>\
                                <input type="text" class="form-control search-input" ng-model="filter" ng-if="config.searchInput"/>\
                                <select class="form-control type-drop" name="" id="" ng-if="config.dropDown">\
                                    <option ng-repeat="d in config.dropList" value="{{d.id}}">{{d.name}}</option>\
                                </select>\
                             </div>\
                             <div class="select-box">\
                                <ul class="one">\
                                    <li ng-class="{current: one.id==oneId}" ng-repeat="one in config.list" onclick="oneClick(one, $event)">\
                                        <area-check area-name="config.areaName" area-id="config.areaId" value="{{one.id}}" item="{{one}}" module="config.checkModule" callback="config.checkCallback">{{one.name}}</area-check>\
                                        <ul class="two" ng-if="one.subs">\
                                            <li ng-repeat="two in one.subs" ng-show="oneId == one.id" onclick="twoClick(two, $event)" ng-class="{current: two.id==twoId, bgfff: !(two.id==twoId)}">\
                                                <area-check area-name="config.areaName" area-id="config.areaId" value="{{two.id}}" item="{{two}}" pid="{{one.id}}" module="config.checkModule" callback="config.checkCallback">{{two.name}}</area-check>\
                                                <ul class="three"  ng-if="two.subs">\
                                                    <li ng-repeat="three in two.subs" ng-show="twoId == two.id">\
                                                        <area-check area-name="config.areaName" area-id="config.areaId" value="{{three.id}}" item="{{three}}" pid="{{two.id}}" grandpid="{{one.id}}" module="config.checkModule" callback="config.checkCallback">{{three.name}}</area-check>\
                                                    </li>\
                                                </ul>\
                                            </li>\
                                        </ul>\
                                    </li>\
                                </ul>\
                             </div>\
                           </div>\
                           <div class="middle fl">\
                               <button class="dsp-btn btn-blue" onclick="config.addAll">全部添加</button>\
                           </div>\
                           <div class="right fl">\
                                <ul class="cl">\
                                    <li class="selected-item" ng-repeat="item in config.areaName">\
                                    {{item}}\
                                    <span onclick="remove($index)"></span>\
                                    </li>\
                                </ul>\
                           </div>\
                       </div>',
            replace: true,
            scope:{
                config: "="
            },
            link: function (scope, element, attrs) {
                scope.oneClick = function (obj, $event) {
                    $event.stopPropagation();
                    scope.oneId = obj.id;
                    if (obj.subs)
                        scope.twoId = obj.subs[0].id;
                };

                scope.twoClick = function (obj, $event) {
                    $event.stopPropagation();
                    scope.twoId = obj.id;
                };

                scope.remove = function (index) {
                    var id = scope.config.areaId[index];
                    var name = scope.config.areaName[index];
                    scope.config.checkCallback(false, $(".check[value='"+ id +"']"), JSON.stringify({"name": name, "id": id}));
                }
            }
        }
    });

    /**
     *  流量来源
     *
     **/
    app.directive("publishSource", function () {
        return {
            restrict: 'E',
            template: '<div class="publish-source">\
                            <div class="filter-box cl">\
                                <input style="border-color: #cfccc7;" ng-show="isSearch" ng-model="media[0]" type="text" placeholder="请输入媒体名称..." class="form-control search-input" />\
                                <span onclick="selectAll()" class="fl">全选</span>\
                                <span onclick="antiSelect()" class="fl">反选</span>\
                                <span onclick="clearAll()" class="fl">全部清空</span>\
                            </div>\
                            <div class="content">\
                                <ul class="cl">\
                                    <li onclick="select($index)" ng-class="{checked: config.selectArr.indexOf(item.id)!=-1, noChecked: config.selectArr.indexOf(item.id)==-1}" class="fl" ng-repeat="item in config.list | filter: media[0]" ng-class="{appli: !!item.iconUrl}" value="{{item.id}}">\
                                        <div class="ps-pic">\
                                            <img ng-class="{icon: item.iconUrl}" ng-src="{{item.logoUrl?item.logoUrl:item.iconUrl}}" title="{{item.appName?item.appName:\'\'}}"/>\
                                        </div>\
                                        <div class="ps-text" title="{{item.name ? item.name:item.appName}}">\
                                            {{item.name ? item.name:item.appName}}\
                                        </div>\
                                    </li>\
                                </ul>\
                            </div>\
                        </div>',
            scope : {
                config: "=",
                isSearch: "=",
                media: "="
            },
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch("scope.config", function (newValue, oldValue) {
                    var list = scope.config.list;
                    var flag;
                    var check = scope.config.selectArr.length != 0 && scope.config.selectArr[0]
                    if (check) {
                        for (var i = 0; i < list.length; i++) {
                            flag = scope.config.selectArr.indexOf(list[i].id) != -1;
                            if (flag) {
                                if (list[i].name || list[i].appName)
                                    scope.config.selectNameArr.push(list[i].name || list[i].appName);
                            }
                        }
                    } else {
                        for (var i = 0; i < list.length; i++) {
                            flag = scope.config.selectArr.indexOf(list[i].id) == -1;
                            if (flag) {
                                scope.config.selectArr.push(list[i].id);
                                if (list[i].name || list[i].appName)
                                    scope.config.selectNameArr.push(list[i].name || list[i].appName);
                            }
                        }
                    }
                    scope.select = function (i) {
                        list = scope.config.list
                        var index = scope.config.selectArr.indexOf(list[i].id);
                        flag = index == -1;
                        if (flag){
                            scope.config.selectArr.push(list[i].id);
                            if (list[i].name || list[i].appName)
                                scope.config.selectNameArr.push(list[i].name || list[i].appName);
            
                        } else {
                            scope.config.selectArr.splice(index, 1);
                            if (list[i].name || list[i].appName)
                                scope.config.selectNameArr.splice(index, 1);
                        }
                    };

                    scope.selectAll = function () {
                        list = scope.config.list
                        for (var i = 0; i < list.length; i++) {
                            flag = scope.config.selectArr.indexOf(list[i].id) == -1;
                            if (flag) {
                                scope.config.selectArr.push(list[i].id);
                                if (list[i].name)
                                    scope.config.selectNameArr.push(list[i].name);
                            }
                        }
                    };

                    scope.clearAll = function () {
                        scope.config.selectArr = [];
                        scope.config.selectNameArr = [];
                    };

                    scope.antiSelect = function () {
                        list = scope.config.list
                        for (var i = 0; i < list.length; i++) {
                            var index = scope.config.selectArr.indexOf(list[i].id);
                            flag = index == -1;
                            if (flag) {
                                scope.config.selectArr.push(list[i].id);
                                if (list[i].name)
                                    scope.config.selectNameArr.push(list[i].name);
                            } else {
                                scope.config.selectArr.splice(index, 1);
                                if (scope.config.selectNameArr)
                                    scope.config.selectNameArr.splice(index, 1);
                            }
                        }
                    };
                });
            }
        }
    })

    /* 小时投放 */
    app.directive('hourDirective', function () {
        return {
            restrict: 'C',
            template: function (element, attrs) {
                return '<div class="d-hour">\
                            <div class="btn-box">\
                                <button onclick="weekend()" class="dsp-btn" ng-class="{\'btn-blue\': config.btnCheckArr.indexOf(\'weekend\') != -1, \'btn-white2\': config.btnCheckArr.indexOf(\'weekend\') == -1}">周末</button>\
                                <button onclick="weeks()" class="dsp-btn" ng-class="{\'btn-blue\': config.btnCheckArr.indexOf(\'weeks\') != -1, \'btn-white2\': config.btnCheckArr.indexOf(\'weeks\') == -1}">工作日</button>\
                                <button onclick="am()" class="dsp-btn" ng-class="{\'btn-blue\': config.btnCheckArr.indexOf(\'am\') != -1, \'btn-white2\': config.btnCheckArr.indexOf(\'am\') == -1}">上午</button>\
                                <button onclick="pm()" class="dsp-btn" ng-class="{\'btn-blue\': config.btnCheckArr.indexOf(\'pm\') != -1, \'btn-white2\': config.btnCheckArr.indexOf(\'pm\') == -1}">下午</button>\
                            </div>\
                            <div class="d-hour-box">\
                                <div class="d-hour d-hour-section">\
                                    <ul>\
                                        <li ng-repeat="s in config.section">\
                                            <div ng-if="$index==0">时间段</div>\
                                            <div ng-if="$index!=0">\
                                                <div id="{{$index}}" onclick="oneClick($index + \'\')" class="d-check fl one-ch" ng-class="{\'d-checked\': config.oneCheckArr.indexOf($index + \'\') != -1 || allCheck}"></div>\
                                                <div class="fl">\
                                                    <span style="line-height: normal; display: block; margin-top: 5px;">{{s.split(" ")[0]}}</span>\
                                                    <span>{{s.split(" ")[1]}}</span>\
                                                </div>\
                                            </div>\
                                        </li>\
                                    </ul>\
                                </div>\
                                <div class="d-hour d-one-hour">\
                                    <ul>\
                                        <li ng-repeat="h in config.oneHour" ng-init="ind=$index">\
                                            <div class="fl" ng-repeat="sub in h">\
                                                <span ng-if="ind==0">单小时</span>\
                                                <div onclick="twoClick(sub, $event)" ng-if="ind!=0" id="{{sub}}" pid="{{ind}}" class="d-check two-check" ng-class="{\'d-checked\': config.twoCheckArr.indexOf(sub) != -1 || allCheck}"></div>\
                                            </div>\
                                        </li>\
                                    </ul>\
                                </div>\
                                <div class="d-hour d-main">\
                                    <ul ng-repeat="w in config.week" ng-init="wid=$index+1">\
                                        <li ng-repeat="i in w" ng-init="ind=$index">\
                                            <span class="fl" ng-if="ind==0">\
                                                <div onclick="weekClick(wid)" class="d-check fl" id="{{wid}}" ng-class="{\'d-checked\': config.weekCheckArr.indexOf(wid + \'\') != -1 || allCheck}"></div>\
                                                <div class="fl" ng-bind="i"></div>\
                                            </span>\
                                            <div ng-if="ind!=0" ng-repeat="h in i" class="fl threeCheck">\
                                                <div onclick="threeClick(h, $event)" pid="{{h.slice(1)}}" ppid="{{ind}}" wid="{{wid}}" id="{{h}}" class="d-check three-check" ng-class="{\'d-checked\': config.threeCheckArr.indexOf(h) != -1}"></div>\
                                            </div>\
                                        </li>\
                                    </ul>\
                                </div>\
                            </div>\
                        </div>'
            },
            scope : {
                checkArr: "=",
                edit: "="
            },
            replace: true,
            link: function (scope, element, attr) {
                scope.config = {
                    section: [0, "00:00 03:59", "04:00 07:59", "08:00 11:59",
                        "12:00 15:59", "16:00 19:59", "20:00 23:59"
                    ],
                    oneCheckArr: [],
                    twoCheckArr: [],
                    weekCheckArr: [],
                    threeCheckArr: [],
                    btnCheckArr: [],
                    oneHour: function () {
                        var arr = [[0]]
                        for (var i = 0; i < 6; i++) {
                            var a = []
                            for (var k = 0; k < 4; k++) {
                                var res = i * 4 + k
                                res = res < 10 ? '0' + res : res + ''
                                a.push(res)
                            }
                            arr.push(a)
                        }
                        console.log(arr)
                        return arr
                    }(),
                    week: function () {
                        var arr = [];
                        for (var i = 1; i < 8; i++) {
                            var w = [weekCh(i)];
                            for (var n = 0; n < 6; n++) {
                                var a = []
                                for (var k = 0; k < 4; k++) {
                                    var r = n * 4 + k
                                    var h = r < 10 ? '0' + r : r + ''
                                    a.push(i + '' + h)
                                }
                                w.push(a)
                            }
                            arr.push(w)
                        }
                        return arr
                    }()
                }
                // 选择周
                scope.weekClick = function (id) {
                    var index = scope.config.weekCheckArr.indexOf(id + '')
                    var checked = index == -1
                    if (index == -1) {
                        scope.config.weekCheckArr.push(id + '')
                    } else {
                        scope.config.weekCheckArr.splice(index, 1)
                    }
                    $('[wid='+ id +']').each(function (i, v) {
                        var i = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                        if (i == -1 && index == -1) {
                            scope.config.threeCheckArr.push($(v).attr('id'))
                        } else if (i != -1 && index != -1) {
                            scope.config.threeCheckArr.splice(i, 1)
                        }
                    })
                    // if (scope.config.weekCheckArr.length == 7) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else if (!checked) {
                    //     scope.allCheck = false
                    //     scope.config.oneCheckArr = []
                    //     scope.config.twoCheckArr = []
                    //     weekOrWeekend()
                    // } else if (checked) {
                    //     scope.allCheck = false
                    //     weekOrWeekend()
                    // }
                    checkedFlag()
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                // 时间段
                scope.oneClick = function (id) {
                    var index = scope.config.oneCheckArr.indexOf(id)
                    if (index == -1) {
                        scope.config.oneCheckArr.push(id)
                    } else {
                        scope.config.oneCheckArr.splice(index, 1)
                    }
                    $('[pid='+ id +']').each(function (i, v) {
                        var d = scope.config.twoCheckArr.indexOf($(v).attr('id'))
                        if (d == -1 && index == -1) {
                            scope.config.twoCheckArr.push($(v).attr('id'))
                        } else if (d != -1 && index != -1) {
                            scope.config.twoCheckArr.splice(d, 1)
                        }
                    })

                    $('[ppid='+ id +']').each(function (i, v) {
                        var i = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                        if (i == -1 && index == -1) {
                            scope.config.threeCheckArr.push($(v).attr('id'))
                        } else if (i != -1 && index != -1) {
                            scope.config.threeCheckArr.splice(i, 1)
                        }
                    })
                    // if (scope.config.oneCheckArr.length == 6) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.weekCheckArr = []
                    //     pmOrAm()
                    // }
                    checkedFlag()
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                // 单小时
                scope.twoClick = function (id, dom) {
                    var index = scope.config.twoCheckArr.indexOf(id)
                    if (index == -1) {
                        scope.config.twoCheckArr.push(id)
                    } else {
                        scope.config.twoCheckArr.splice(index, 1)
                    }
                    $('[pid='+ id +']').each(function (i, v) {
                        var i = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                        if (i == -1 && index == -1) {
                            scope.config.threeCheckArr.push($(v).attr('id'))
                        } else if (i != -1 && index != -1) {
                            scope.config.threeCheckArr.splice(i, 1)
                        }
                    })
                    // if (scope.config.twoCheckArr.length == 24) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.weekCheckArr = []
                    //     pmOrAm()
                    // }
                    checkedFlag()
                    var pid = $(dom.target).attr('pid')
                    index = scope.config.oneCheckArr.indexOf(pid)
                    // setTimeout(function () {
                    //     var l = $('.d-checked[pid='+ pid +']').length
                    //     scope.$apply(function () {
                    //         if (l == 4) {
                    //             if (index == -1) {
                    //                 scope.config.oneCheckArr.push(pid)
                    //             }
                    //         } else {
                    //             if (index != -1) {
                    //                 scope.config.oneCheckArr.splice(index, 1)
                    //             }
                    //         }
                    //     })
                    // }, 100)
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                // 单点
                scope.threeClick = function (id, dom) {
                    var index = scope.config.threeCheckArr.indexOf(id)
                    if (index == -1) {
                        scope.config.threeCheckArr.push(id)
                    } else {
                        scope.config.threeCheckArr.splice(index, 1)
                    }
                    dom = $(dom.target)
                    var pid = dom.attr('pid')
                    var ppid = dom.attr('ppid')
                    var wid = dom.attr('wid')
                    setTimeout(function () {
                        var pIndex = scope.config.twoCheckArr.indexOf(pid)
                        var ppIndex = scope.config.oneCheckArr.indexOf(ppid)
                        var wIndex = scope.config.weekCheckArr.indexOf(wid)
                        var pLen = $('.d-checked[pid='+ pid +']').length
                        var ppLen = $('.d-checked[ppid='+ ppid +']').length
                        var wLen = $('.d-checked[wid='+ wid +']').length
                        scope.$apply(function () {
                        //     if (pLen == 7) {
                        //         if (pIndex == -1) {
                        //             scope.config.twoCheckArr.push(pid)
                        //         }
                        //     } else {
                        //         if (pIndex != -1) {
                        //             scope.config.twoCheckArr.splice(pIndex, 1)
                        //         }
                        //     }

                        //     if (ppLen == 28) {
                        //         if (ppIndex == -1) {
                        //             scope.config.oneCheckArr.push(ppid)
                        //         } 
                        //     } else {
                        //         if (ppIndex != -1) {
                        //             scope.config.oneCheckArr.splice(ppIndex, 1)
                        //             if (ppid * 1 > 3) {
                        //                 var ind = scope.config.btnCheckArr.indexOf('pm')
                        //                 if (ind != -1) {
                        //                     scope.config.btnCheckArr.splice(ind, 1)
                        //                 }
                        //             } else {
                        //                 var ind = scope.config.btnCheckArr.indexOf('am')
                        //                 if (ind != -1) {
                        //                     scope.config.btnCheckArr.splice(ind, 1)
                        //                 }
                        //             }
                        //         }
                        //     }

                        //     if (wLen == 24) {
                        //         if (wIndex == -1) {
                        //             scope.config.weekCheckArr.push(wid)
                        //         }
                        //     } else {
                        //         if (wIndex != -1) {
                        //             scope.config.weekCheckArr.splice(wIndex, 1)
                        //             if (wid * 1 > 5) {
                        //                 var ind = scope.config.btnCheckArr.indexOf('weekend')
                        //                 if (ind != -1) {
                        //                     scope.config.btnCheckArr.splice(ind, 1)
                        //                 }
                        //             } else {
                        //                 var ind = scope.config.btnCheckArr.indexOf('weeks')
                        //                 if (ind != -1) {
                        //                     scope.config.btnCheckArr.splice(ind, 1)
                        //                 }
                        //             }
                        //         }
                        //     }

                            // if (scope.config.threeCheckArr.length == 168) {
                            //     scope.allCheck = true
                            //     allCheck()
                            // } else {
                            //     scope.allCheck = false
                            // }
                            checkedFlag()
                        })
                    }, 100)
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                // 按钮周末
                scope.weekend = function () {
                    var index = scope.config.btnCheckArr.indexOf('weekend')
                    var isCheck = index == -1
                    if (index == -1) {
                        scope.config.btnCheckArr.push('weekend')
                        index = scope.config.weekCheckArr.indexOf('6')
                        if (index == -1) {
                            scope.config.weekCheckArr.push('6')
                        }
                        index = scope.config.weekCheckArr.indexOf('7')
                        if (index == -1) {
                            scope.config.weekCheckArr.push('7')
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') / 100)
                            if (flag > 5 && flag > 0) {
                                if (scope.config.threeCheckArr.indexOf($(v).attr('id')) == -1) {
                                    scope.config.threeCheckArr.push($(v).attr('id'))
                                }
                            }
                        })
                    } else {
                        scope.config.btnCheckArr.splice(index, 1)
                        index = scope.config.weekCheckArr.indexOf('6')
                        if (index != -1) {
                            scope.config.weekCheckArr.splice(index, 1)
                        }
                        index = scope.config.weekCheckArr.indexOf('7')
                        if (index != -1) {
                            scope.config.weekCheckArr.splice(index, 1)
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') / 100)
                            if (flag > 5 && flag > 0) {
                                index = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                                if (index != -1) {
                                    scope.config.threeCheckArr.splice(index, 1)
                                }
                            }
                        })
                    }
                    checkedFlag()
                    // if (scope.config.threeCheckArr.length == 168) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.oneCheckArr = []
                    //     scope.config.twoCheckArr = []
                    //     if (isCheck) {
                    //         scope.config.weekCheckArr = ['6', '7']
                    //     } else if (scope.config.btnCheckArr.indexOf('weeks') != -1) {
                    //         scope.config.weekCheckArr = ['1', '2', '3', '4', '5']
                    //         scope.config.btnCheckArr = ['weeks']
                    //     } else {
                    //         scope.config.btnCheckArr = []
                    //         scope.config.weekCheckArr = []
                    //     }
                    // }
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                // 按钮工作日
                scope.weeks = function () {
                    var index = scope.config.btnCheckArr.indexOf('weeks')
                    var isCheck = index == -1
                    if (index == -1) {
                        scope.config.btnCheckArr.push('weeks')
                        for (var i = 1; i < 6; i++) {
                            index = scope.config.weekCheckArr.indexOf(i + '')
                            if (index == -1) {
                                scope.config.weekCheckArr.push(i + '')
                            }
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') / 100)
                            if (flag < 6 && flag > 0) {
                                if (scope.config.threeCheckArr.indexOf($(v).attr('id')) == -1) {
                                    scope.config.threeCheckArr.push($(v).attr('id'))
                                }
                            }
                        })
                    } else {
                        scope.config.btnCheckArr.splice(index, 1)
                        for (var i = 1; i < 6; i++) {
                            index = scope.config.weekCheckArr.indexOf(i + '')
                            if (index != -1) {
                                scope.config.weekCheckArr.splice(index, 1)
                            }
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') / 100)
                            if (flag < 6 && flag > 0) {
                                index = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                                if (index != -1) {
                                    scope.config.threeCheckArr.splice(index, 1)
                                }
                            }
                        })
                    }
                    checkedFlag()
                    // if (scope.config.threeCheckArr.length == 168) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.oneCheckArr = []
                    //     scope.config.twoCheckArr = []
                    //     if (isCheck) {
                    //         scope.config.weekCheckArr = ['1', '2', '3', '4', '5']
                    //     } else if (scope.config.btnCheckArr.indexOf('weekend') != -1) {
                    //         scope.config.weekCheckArr = ['6', '7']
                    //         scope.config.btnCheckArr = ['weekend']
                    //     } else {
                    //         scope.config.weekCheckArr = []
                    //         scope.config.btnCheckArr = []
                    //     }
                    // }
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                //上午
                scope.am = function () {
                    var index = scope.config.btnCheckArr.indexOf('am')
                    var isCheck = index == -1
                    if (index == -1) {
                        scope.config.btnCheckArr.push('am')
                        for (var i = 1; i < 4; i++) {
                            index = scope.config.oneCheckArr.indexOf('' + i)
                            if (index == -1) {
                                scope.config.oneCheckArr.push('' + i)
                            }
                            $('[pid='+ (i + '') +']').each(function (i, v) {
                                var d = scope.config.twoCheckArr.indexOf($(v).attr('id'))
                                if (d == -1) {
                                    scope.config.twoCheckArr.push($(v).attr('id'))
                                }
                            })
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') % 100)
                            if (flag < 12 && $(v).attr('pid')) {
                                if (scope.config.threeCheckArr.indexOf($(v).attr('id')) == -1) {
                                    scope.config.threeCheckArr.push($(v).attr('id'))
                                }
                            }
                        })
                    } else {
                        scope.config.btnCheckArr.splice(index, 1)
                        for (var i = 1; i < 4; i++) {
                            index = scope.config.oneCheckArr.indexOf(i + '')
                            if (index != -1) {
                                scope.config.oneCheckArr.splice(index, 1)
                            }
                            $('[pid='+ (i + '') +']').each(function (i, v) {
                                var d = scope.config.twoCheckArr.indexOf($(v).attr('id'))
                                if (d != -1) {
                                    scope.config.twoCheckArr.splice(d, 1)
                                }
                            })
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') % 100)
                            if (flag < 12) {
                                index = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                                if (index != -1) {
                                    scope.config.threeCheckArr.splice(index, 1)
                                }
                            }
                        })
                    }
                    checkedFlag()
                    // if (scope.config.threeCheckArr.length == 168) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.weekCheckArr = []
                    //     if (!isCheck) {
                    //         index = scope.config.btnCheckArr.indexOf('am')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //         index = scope.config.btnCheckArr.indexOf('weeks')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //         index = scope.config.btnCheckArr.indexOf('weekend')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //     }
                    // }
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }
                //下午
                scope.pm = function () {
                    var index = scope.config.btnCheckArr.indexOf('pm')
                    var isCheck = index == -1
                    if (index == -1) {
                        scope.config.btnCheckArr.push('pm')
                        for (var i = 4; i < 7; i++) {
                            index = scope.config.oneCheckArr.indexOf('' + i)
                            if (index == -1) {
                                scope.config.oneCheckArr.push('' + i)
                            }
                            $('[pid='+ (i + '') +']').each(function (i, v) {
                                var d = scope.config.twoCheckArr.indexOf($(v).attr('id'))
                                if (d == -1) {
                                    scope.config.twoCheckArr.push($(v).attr('id'))
                                }
                            })
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') % 100)
                            if (flag > 11) {
                                if (scope.config.threeCheckArr.indexOf($(v).attr('id')) == -1) {
                                    scope.config.threeCheckArr.push($(v).attr('id'))
                                }
                            }
                        })
                    } else {
                        scope.config.btnCheckArr.splice(index, 1)
                        for (var i = 4; i < 7; i++) {
                            index = scope.config.oneCheckArr.indexOf(i + '')
                            if (index != -1) {
                                scope.config.oneCheckArr.splice(index, 1)
                            }
                            $('[pid='+ (i + '') +']').each(function (i, v) {
                                var d = scope.config.twoCheckArr.indexOf($(v).attr('id'))
                                if (d != -1) {
                                    scope.config.twoCheckArr.splice(d, 1)
                                }
                            })
                        }
                        $(".d-main .d-check").each(function (i, v) {
                            var flag = Math.floor($(v).attr('id') % 100)
                            if (flag > 11) {
                                index = scope.config.threeCheckArr.indexOf($(v).attr('id'))
                                if (index != -1) {
                                    scope.config.threeCheckArr.splice(index, 1)
                                }
                            }
                        })
                    }
                    checkedFlag()
                    // if (scope.config.threeCheckArr.length == 168) {
                    //     scope.allCheck = true
                    //     allCheck()
                    // } else {
                    //     scope.allCheck = false
                    //     scope.config.weekCheckArr = []
                    //     if (!isCheck) {
                    //         index = scope.config.btnCheckArr.indexOf('pm')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //         index = scope.config.btnCheckArr.indexOf('weeks')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //         index = scope.config.btnCheckArr.indexOf('weekend')
                    //         if (index != -1) {
                    //             scope.config.btnCheckArr.splice(index, 1)
                    //         }
                    //     }
                    // }
                    scope.checkArr = scope.config.threeCheckArr.join(',').split(',')
                }

                if (scope.edit) {
                    var timer = setInterval(function () {
                    if ($('.three-check').length == 168 && scope.checkArr.length != 0) {
                            clearInterval(timer)
                            var arr = scope.checkArr
                            for (var i = 0; i < arr.length; i++) {
                                var dom = {
                                    target: $('[id='+ arr[i] * 1 +']')[0]
                                }
                                scope.threeClick(arr[i], dom)
                            }
                        }
                    }, 100)
                }

                function allCheck() {
                    scope.config.oneCheckArr = ['1', '2', '3', '4', '5', '6']
                    scope.config.twoCheckArr = function () {
                        var a = []
                        for (var i = 0; i < 6; i++) {
                            for (var k = 0; k < 4; k++) {
                                var res = i * 4 + k
                                res = res < 10 ? '0' + res : res + ''
                                a.push(res)
                            }
                        }
                        return a
                    }()
                    scope.config.weekCheckArr = ['1', '2', '3', '4', '5', '6', '7']
                    scope.config.btnCheckArr = ['weekend', 'weeks', 'am', 'pm']
                }

                function weekOrWeekend() {
                    var ws = scope.config.weekCheckArr
                    var flag = {
                        week: 0,
                        weekend: 0
                    }
                    for (var i = 0, l = ws.length; i < l; i++) {
                        if (ws[i] * 1 < 6) {
                            flag.week++
                        } else {
                            flag.weekend++
                        }
                    }
                    if (flag.week == 5) {
                        scope.config.btnCheckArr = ['weeks']
                    } else if (flag.weekend == 2) {
                        scope.config.btnCheckArr = ['weekend']
                    } else {
                        scope.config.btnCheckArr = []
                    }
                }

                function checkedFlag() {
                    for (var i = 1; i < 8; i++) {
                        var len = getCheckLenth(scope.config.threeCheckArr, '^' + i)
                        var ind = scope.config.weekCheckArr.indexOf(i + '')
                        if (len == 24) {
                            if (ind == -1) {
                                scope.config.weekCheckArr.push(i + '')
                            }
                        } else {
                            if (ind != -1) {
                                scope.config.weekCheckArr.splice(ind, 1)
                            }
                        }
                    }

                    for (var i = 0; i < 24; i++) {
                        var id = i < 10 ? '0' + i : '' + i
                        var len = getCheckLenth(scope.config.threeCheckArr, id + '$')
                        var ind = scope.config.twoCheckArr.indexOf(id)
                        if (len == 7) {
                            if (ind == -1) {
                                scope.config.twoCheckArr.push(id)
                            }
                        } else {
                            if (ind != -1) {
                                scope.config.twoCheckArr.splice(ind, 1)
                            }
                        }
                    }

                    for (var i = 1; i < 7; i++) {
                        var arr = ['', '00|01|02|03', '04|05|06|07', '08|09|10|11', 
                            '12|13|14|15', '16|17|18|19', '20|21|22|23' 
                        ]
                        var len = getCheckLenth(scope.config.twoCheckArr, arr[i])
                        var ind = scope.config.oneCheckArr.indexOf(i + '')
                        if (len == 4) {
                            if (ind == -1) {
                                scope.config.oneCheckArr.push(i + '')
                            }
                        } else {
                            if (ind != -1) {
                                scope.config.oneCheckArr.splice(ind, 1)
                            }
                        }
                    }

                    for (var i = 0; i < 4; i++) {
                        var arr = ['^6|^7', '^1|^2|^3|^4|^5', '00$|01$|02$|03$|04$|05$|06$|07$|08$|09$|10$|11$', '12$|13$|14$|15$|16$|17$|18$|19$|20$|21$|22$|23$']
                        var btnArr = ['weekend', 'weeks', 'am', 'pm']
                        var fLen = [48, 120, 84, 84]
                        var len = getCheckLenth(scope.config.threeCheckArr, arr[i])
                        var ind = scope.config.btnCheckArr.indexOf(btnArr[i])
                        if (len == fLen[i]) {
                            if (ind == -1) {
                                scope.config.btnCheckArr.push(btnArr[i])
                            }
                        } else {
                            if (ind != -1) {
                                scope.config.btnCheckArr.splice(ind, 1)
                            }
                        }
                    }
                }

                function pmOrAm() {
                    var arr = scope.config.twoCheckArr
                    var flag = {
                        am: 0,
                        pm: 0
                    }
                    for (var i = 0, l = arr.length; i < l; i++) {
                        if (arr[i] * 1 < 12) {
                            flag.am++
                        } else {
                            flag.pm++
                        }
                    }
                    if (flag.am == 12) {
                        scope.config.btnCheckArr = ['am']
                    } else if (flag.pm == 12) {
                        scope.config.btnCheckArr = ['pm']
                    } else {
                        scope.config.btnCheckArr = []
                    }
                }

                function weekCh(i) {
                    var arr = ['', '周一', '周二', '周三', '周四', 
                        '周五', '周六', '周日'];
                    return arr[i]
                }

                function getCheckLenth(arr, match) {
                    var res = 0
                    match = new RegExp(match)
                    for (var i = 0, l = arr.length; i < l; i++) {
                        if (match.test(arr[i])) {
                            res++
                        }
                    }
                    return res
                }
            }
        }
    })

    // 人群包
    app.directive('crowdPkg', function () {
        return {
            restrict: 'C',
            template:   '<div class="crowd-pkg-box">\
                            <ul ng-if="list.length != 0" class="crowd-pkg-list cl">\
                                <li ng-class="{\'pkg-checked\': config.crowd == i.id + \'\'}" onclick="selectRadio(i)" class="cl" ng-repeat="i in list">\
                                    <div class="radio-box">\
                                        <radio module="config.crowd" value="{{i.id + \'\'}}"></radio>\
                                    </div>\
                                    <div class="name-box">\
                                        <img ng-src="{{i.icon}}" /><br>\
                                        <span ng-bind="i.name"></span>\
                                    </div>\
                                    <div class="remark-box" ng-class="{\'line-hei\': i.description.length > 22}">\
                                        <span ng-bind="i.description"></span>\
                                    </div>\
                                    <span class="label-icon" ng-class="{\'icon-star\': i.tag == \'新秀包\', \'icon-fire\': i.tag == \'热销包\', \'icon-crown\': i.tag == \'明星包\'}">\
                                    </span>\
                                </li>\
                            </ul>\
                            <ul ng-if="list.length == 0">\
                                <div style="text-align: center; padding: 20px 0px;">\
                                    <span style="font-size: 14px; color: #bfbfbf;">暂无人群包</span>\
                                </div>\
                            </ul>\
                        </div>',
            scope: {
                callback: '=',
                list: '=',
                edit: '=',
                spaceIds: '=',
                viewdata: '='
            },
            link: function (scope, element, attr) {
                scope.config = {
                    crowd: ''
                }

                scope.selectRadio = function (val) {
                    //用来订单第四步展示
                    scope.viewdata = val
                    //用来判断选中
                    scope.config.crowd = val.id + ''
                    var arr = []
                    for (var i = 0, l = val.appInfo.length; i < l; i++) {
                        arr.push(val.appInfo[i].dspSpaceID)
                    }
                    if (arr.length == 1) {
                        scope.spaceIds = arr[0] 
                    } else {
                        scope.spaceIds = arr.join(',') 
                    }
                    scope.callback && scope.callback(val.id + '')
                }

                var timer = setInterval(function () {
                    if ($('.crowd-pkg-box .radio-box')[0] && scope.edit) {
                        clearInterval(timer)
                        scope.$apply(function () {
                            scope.config.crowd = scope.edit
                            for (var i = 0, l = scope.list.length; i < l; i++) {
                                if (scope.list[i].id == scope.edit) {
                                    scope.viewdata = scope.list[i]
                                }
                            }
                        })
                    }
                })
            }
        }
    })

    // 行业包
    app.directive('industryPkg', function () {
        return {
            restrict: 'C',
            template:   '<div class="industry-pkg-box">\
                            <ul ng-if="list.length != 0" class="industry-pkg-list cl">\
                                <li onclick="selectRadio(i)" class="cl" ng-repeat="i in list">\
                                    <div class="radio-box">\
                                        <radio module="config.industry" value="{{i.id + \'\'}}"></radio>\
                                    </div>\
                                    <div ng-class="{\'pkg-checked\': config.industry == i.id + \'\'}" class="app-list cl">\
                                        <div class="name-box">\
                                            <span ng-bind="i.name"></span>\
                                        </div>\
                                        <div class="app-box cl">\
                                            <ul class="cl" style="width: {{i.appInfo.length * 126 + 20}}px">\
                                                <li ng-repeat="s in i.appInfo">\
                                                    <div class="img-box">\
                                                        <img ng-src="{{s.appIcon}}" />\
                                                    </div>\
                                                    <div class="app-name-box" ng-bind="s.appName">\
                                                    </div>\
                                                </li>\
                                            </ul>\
                                        </div>\
                                    </div>\
                                </li>\
                            </ul>\
                            <ul ng-if="list.length == 0">\
                                <div style="text-align: center; padding: 20px 0px;">\
                                    <span style="font-size: 14px; color: #bfbfbf;">暂无行业包</span>\
                                </div>\
                            </ul>\
                        </div>',
            scope: {
                callback: '=',
                list: '=',
                edit: '=',
                spaceIds: '=',
                viewdata: '='
            },
            link: function (scope, element, attr) {
                scope.config = {
                    industry: ''
                }

                scope.selectRadio = function (val) {
                    //用于订单第四步展示
                    scope.viewdata = val

                    scope.config.industry = val.id
                    var arr = []
                    for (var i = 0, l = val.appInfo.length; i < l; i++) {
                        arr.push(val.appInfo[i].dspSpaceID)
                    }
                    if (arr.length == 1) {
                        scope.spaceIds = arr[0] 
                    } else {
                        scope.spaceIds = arr.join(',') 
                    }
                    scope.callback && scope.callback(val.id + '')
                }

                var timer = setInterval(function () {
                    if ($('.industry-pkg-box .radio-box')[0] && scope.edit) {
                        clearInterval(timer)
                        scope.$apply(function () {
                            scope.config.industry = scope.edit
                            for (var i = 0, l = scope.list.length; i < l; i++) {
                                if (scope.list[i].id == scope.edit) {
                                    scope.viewdata = scope.list[i]
                                }
                            }
                        })
                    }
                })
            }
        }
    })

    
    app.directive("lpInfoBox",function(){
        return {
            restrict: 'E',
            template: '<div class="lp-info-box">\
                    <div class="info-content">\
                        <div class="info-title">\
                            页面嵌入监测代码后，需要对落地页添加宏后填写至素材落地页地址中以便监测生效；<br>\
                            会遇到如下两种情况：\
                        </div>\
                        <h3><span>1</span>当落地页地址中存在"?"，如`http://www.a.com/?a=b&c=d....x=y` 添加如下字符串至末尾</h3>\
                        <p>&adhub_IMEI=__IMEI__&adhub_IMEI_MD5=__IMEI_MD5__&adhub_ANDROIDID=__ANDROIDID__&adhub_ANDROIDID_MD5=__ANDROIDID_MD5__&adhub_IDFA=__IDFA__&adhub_IDFA_MD5=__IDFA_MD5__</p>\
                        <p class="info-font">最终结果为：</p>\
                        <p>http://www.a.com/?a=b&c=d....x=y&adhub_IMEI=__IMEI__&adhub_IMEI_MD5=__IMEI_MD5__&adhub_ANDROIDID=__ANDROIDID__&adhub_ANDROIDID_MD5=__ANDROIDID_MD5__&adhub_IDFA=__IDFA__&adhub_IDFA_MD5=__IDFA_MD5__</p>\
                        <h3><span>2</span>当落地页地址不存在"?"时，比如`http://www.a.com/1/2/3`，添加如下字符串至末尾</h3>\
                        <p>?adhub_IMEI=__IMEI__&adhub_IMEI_MD5=__IMEI_MD5__&adhub_ANDROIDID=__ANDROIDID__&adhub_ANDROIDID_MD5=__ANDROIDID_MD5__&adhub_IDFA=__IDFA__&adhub_IDFA_MD5=__IDFA_MD5__</p>\
                        <p class="info-font">最终结果为：</p>\
                        <p>http://www.a.com/1/2/3?adhub_IMEI=__IMEI__&adhub_IMEI_MD5=__IMEI_MD5__&adhub_ANDROIDID=__ANDROIDID__&adhub_ANDROIDID_MD5=__ANDROIDID_MD5__&adhub_IDFA=__IDFA__&adhub_IDFA_MD5=__IDFA_MD5__</p>\
                    </div>\
                    <div class="btn-group">\
                        <button class="dsp-btn btn-red" onclick="closeLayer()">关闭</button>\
                    </div>\
                </div>',
            replace: true,
            link:function(scope, element, attrs){
                scope.closeLayer = function() {
                   layer.closeAll()
                }
            }
        }
    });

    app.directive('onFinishRenderFilters', function ($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        scope.$emit('ngRepeatFinished');
                    });
                }
            }
        };
    });

    // dom渲染结束
    app.directive('onFinishRender', function ($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        scope.$emit('ngFinishRender');
                    });
                }
            }
        };
    });
    // video渲染结束
    app.directive('onFinishRenderVideo', function ($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        scope.$emit('ngFinishRenderVideo');
                    });
                }
            }
        };
    });
})();